package goods_service

import (
	"errors"
	"fmt"
	"io"
	"log"
	"myserver/app/model"
	"myserver/app/types"
	"myserver/pkg/global"
	"myserver/pkg/utils"
	"net/http"
	"strings"

	"github.com/spf13/viper"
)

type GoodsService struct {
	Barcode string `json:"barCode"`
}

func (this *GoodsService) AddGoods() error {
	var (
		codes []string
		g     []types.SysGoods
	)

	codes = append(codes, this.Barcode)
	goods, err := model.FindGoodsByBarcode(codes)
	if err != nil {
		return err
	}
	if len(goods) == 0 {
		goods, s := GetGoodsByBarCode(this.Barcode)
		if s != nil {
			fmt.Println(s)
			return s
		}
		goods.Uuid = utils.GetUuid()
		goods.Count = 1
		return model.AddGoods(&goods)
	} else {
		data := goods[0]
		data.Count += 1
		g = append(g, data)
		return model.UpDataGoods(&g)
	}

}

// 请求一个商品信息
func GetGoodsByBarCode(code string) (types.SysGoods, error) {
	goods := types.SysGoods{}
	s := fmt.Sprintf("%s?barcode=%s&app_id=%s&app_secret=%s", global.CONFIG.ApiGoods.Url, code, global.CONFIG.ApiGoods.AppId, global.CONFIG.ApiGoods.AppSecret)
	resp, err := http.Get(s)
	if err != nil {
		log.Println(err)
		return goods, err
	}

	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)

	if err != nil {
		return goods, err
	}
	v := viper.New()
	v.SetConfigType("json")
	str := string(body)
	err = v.ReadConfig(strings.NewReader(str))
	if err != nil {
		return goods, err
	}
	data := v.Get("data")
	if data == nil {
		mesg := v.Get("msg").(string)
		return goods, errors.New(mesg)
	}
	goods.GoodsName = v.Get("data.goodsName").(string)
	goods.Barcode = v.Get("data.barcode").(string)
	goods.Price = v.Get("data.price").(string)
	goods.Brand = v.Get("data.brand").(string)
	goods.Supplier = v.Get("data.supplier").(string)
	goods.Standard = v.Get("data.standard").(string)
	return goods, nil
}
